package com.dog.basics.service.mtkj.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.mtkj.OrderComplaintFromDto;
import com.dog.basics.bean.dto.admin.mtkj.OrderComplaintStatusDto;
import com.dog.basics.bean.model.common.DogUser;
import com.dog.basics.bean.model.mtkj.*;
import com.dog.basics.bean.model.sys.SysUser;
import com.dog.basics.bean.vo.admin.mtkj.OrderComplaintVo;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.common.DogUserMapper;
import com.dog.basics.dao.mtkj.MtDeviceFlowingWaterMapper;
import com.dog.basics.dao.mtkj.MtDeviceHospitalMapper;
import com.dog.basics.dao.mtkj.MtDeviceOrderMapper;
import com.dog.basics.dao.mtkj.MtOrderComplaintMapper;
import com.dog.basics.dao.sys.SysUserMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.common.WeChatMiniService;
import com.dog.basics.service.mtkj.IMtOrderComplaintService;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备订单异常反馈表 服务实现类
 * </p>
 *
 * @author wph
 * @since 2020-10-07
 */
@Service
@AllArgsConstructor
public class MtOrderComplaintServiceImpl extends ServiceImpl<MtOrderComplaintMapper, MtOrderComplaint> implements IMtOrderComplaintService {
    private final DogUserMapper dogUserMapper;
    private final SysUserMapper sysUserMapper;
    private final WeChatMiniService weChatMiniService;
    private final MtDeviceHospitalMapper mtDeviceHospitalMapper;
    private final MtDeviceOrderMapper mtDeviceOrderMapper;
    private final MtDeviceFlowingWaterMapper mtDeviceFlowingWaterMapper;


    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param userIds
     */
    public List<Long> getuserIdsWhere(String name, String mobile, List<Long> userIds) {
        List<Long> collect = dogUserMapper.selectList(Wrappers.<DogUser>lambdaQuery().like(StrUtil.isNotBlank(mobile), DogUser::getUserMobile, mobile).like(StrUtil.isNotBlank(name), DogUser::getNickName, name)).stream().map(e -> e.getUserId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            userIds = collect;
        } else {
            userIds.add(-2L);
        }
        return userIds;
    }

    /**
     * 分页的条件公用类
     *
     * @param name,mobile
     * @param orderIds
     */
    public List<Long> getorderIdsWhere(String name, List<Long> orderIds) {
        List<Long> collect = mtDeviceOrderMapper.selectList(Wrappers.<MtDeviceOrder>lambdaQuery().like(StrUtil.isNotBlank(name), MtDeviceOrder::getOrderNo, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            orderIds = collect;
        } else {
            orderIds.add(-2L);
        }
        return orderIds;
    }

    /**
     * @Description: 分页设备订单异常反馈
     * @Param: status
     * @return: IPage<OrderComplaintVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<OrderComplaintVo> getPageList(PageParam page, OrderComplaintFromDto obj) {
        List<Long> orderId = CollUtil.newArrayList();
        //权限判断
        if (SecurityUtils.getSysUser().getAccountType() == 2) {
            orderId = mtDeviceOrderMapper.selectList(Wrappers.<MtDeviceOrder>lambdaQuery().eq(MtDeviceOrder::getOrderAgentUserId, SecurityUtils.getSysUser().getUserId())).stream().map(e -> e.getId()).collect(Collectors.toList());
            if (CollUtil.isEmpty(orderId)) {
                orderId.add(-2L);
            }
        }
        // 判断所属用户ID
        List<Long> userIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getOrderUserName()) || StrUtil.isNotBlank(obj.getOrderUserMobile())) {
            userIds = getuserIdsWhere(obj.getOrderUserName(), obj.getOrderUserMobile(), userIds);
        }
        // 判断所属订单ID
        List<Long> orderIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getOrderNo())) {
            orderIds = getorderIdsWhere(obj.getOrderNo(), orderIds);
        }
        IPage iPage = this.page(page, Wrappers.<MtOrderComplaint>lambdaQuery()
                .in(CollUtil.isNotEmpty(orderId), MtOrderComplaint::getOrderId, orderId)
                .in(CollUtil.isNotEmpty(userIds), MtOrderComplaint::getUserId, userIds)
                .in(CollUtil.isNotEmpty(orderIds), MtOrderComplaint::getOrderId, orderIds)
                .eq(ObjectUtil.isNotNull(obj.getComplaintState()), MtOrderComplaint::getComplaintState, obj.getComplaintState())
                .eq(ObjectUtil.isNotNull(obj.getOrderId()), MtOrderComplaint::getOrderId, obj.getOrderId())
                .eq(ObjectUtil.isNotNull(obj.getUserId()), MtOrderComplaint::getUserId, obj.getUserId())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), MtOrderComplaint::getComplaintTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), MtOrderComplaint::getCreateTime));
        List<MtOrderComplaint> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            OrderComplaintVo newsVo = BeanUtil.toBean(e, OrderComplaintVo.class);
            //查询
            DogUser dogUser = dogUserMapper.selectById(e.getUserId());
            MtDeviceOrder mtDeviceOrder = mtDeviceOrderMapper.selectById(e.getOrderId());
            MtDeviceHospital mtDeviceHospital = mtDeviceHospitalMapper.selectById(ObjectUtil.isNotNull(mtDeviceOrder)?mtDeviceOrder.getOrderDeviceHospitalId():-1L);
            SysUser sysUser = sysUserMapper.selectById(ObjectUtil.isNotNull(mtDeviceOrder)?mtDeviceOrder.getOrderAgentUserId():-1L);
            newsVo.setOrderUserName(ObjectUtil.isNotNull(dogUser) ? dogUser.getNickName() : "");
            newsVo.setOrderUserMobile(ObjectUtil.isNotNull(dogUser) ? dogUser.getUserMobile() : "");
            newsVo.setOrderAgentUserName(ObjectUtil.isNotNull(sysUser) ? sysUser.getUsername() : "");
            newsVo.setOrderDeviceHospitalName(ObjectUtil.isNotNull(mtDeviceHospital) ? mtDeviceHospital.getHospitalName() : "");
            newsVo.setOrderNo(ObjectUtil.isNotNull(mtDeviceOrder) ? mtDeviceOrder.getOrderNo() : "");
            newsVo.setOrderState(ObjectUtil.isNotNull(mtDeviceOrder) ? mtDeviceOrder.getOrderState() : null);
            newsVo.setOrderPayMoney(ObjectUtil.isNotNull(mtDeviceOrder) ? mtDeviceOrder.getOrderPayMoney() : null);
            newsVo.setOrderPayState(ObjectUtil.isNotNull(mtDeviceOrder) ? mtDeviceOrder.getOrderPayState() : null);
            newsVo.setOrderDeviceHospitalId((ObjectUtil.isNotNull(mtDeviceHospital) ? mtDeviceHospital.getId() : -1L));
            newsVo.setUserId(ObjectUtil.isNotNull(sysUser) ? sysUser.getUserId() : -1L);
            return newsVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: 新增设备订单异常反馈
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveObj(Long id) {
        MtDeviceOrder mtDeviceOrder = mtDeviceOrderMapper.selectById(id);
        Validator.validateNotNull(mtDeviceOrder, "订单不存在!");
        mtDeviceOrder.setOrderState(2);
        Validator.validateTrue(retBool(mtDeviceOrderMapper.updateById(mtDeviceOrder)), "设备订单异常反馈失败!");
        //判断是否已经反馈
        List<MtOrderComplaint> list = this.list(Wrappers.<MtOrderComplaint>lambdaQuery().eq(MtOrderComplaint::getOrderId, id).eq(MtOrderComplaint::getUserId, SecurityUtils.getUser().getUserId()));
        Validator.validateFalse(CollUtil.isNotEmpty(list), "此订单已经反馈");
        MtOrderComplaint mtOrderComplaint = new MtOrderComplaint();
        mtOrderComplaint.setOrderId(id);
        mtOrderComplaint.setUserId(SecurityUtils.getUser().getUserId());
        mtOrderComplaint.setComplaintTime(DateUtil.currentSeconds());
        mtOrderComplaint.setComplaintState(0);
        mtOrderComplaint.setCreateTime(DateUtil.currentSeconds());
        mtOrderComplaint.setCreateBy(SecurityUtils.getUser().getUserId());
        Validator.validateTrue(this.save(mtOrderComplaint), "设备订单异常反馈失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 删除设备订单异常反馈
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        MtOrderComplaint dogNews = this.getById(id);
        Validator.validateNotNull(dogNews, "无此数据!");
        Validator.validateTrue(this.removeById(id), "数据删除失败!");
        return Boolean.TRUE;
    }

    /**
     * @Description: 确认退款(pc)
     * @Param: OrderFromDto
     * @return: IPage<PlatePageVo>
     * @Author: wph
     * @Date:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public Boolean pcReturnObj(Long id) {
        MtOrderComplaint dogNews = this.getById(id);
        Validator.validateNotNull(dogNews, "无此数据!");
        Validator.validateEqual(dogNews.getComplaintState(), 1, "只有处理完成才能退款!");
        AlipayTradeRefundResponse alipayTradeRefundResponse = new AlipayTradeRefundResponse();
        MtDeviceOrder mtDeviceOrder = mtDeviceOrderMapper.selectById(dogNews.getOrderId());
        Validator.validateNotNull(mtDeviceOrder, "订单不存在!");
        Validator.validateEqual(mtDeviceOrder.getOrderPayState(), 1, "订单还未支付不能退款!");
        mtDeviceOrder.setOrderState(5);
        Validator.validateTrue(retBool(mtDeviceOrderMapper.updateById(mtDeviceOrder)), "退款开始失败!");
        //设置退款信息
        WxPayRefundRequest wxpayrefundrequest = new WxPayRefundRequest();
        //设备标识
        //wxpayrefundrequest.setDeviceInfo(orderinfoentity.getDeviceId());
        //商户订单号
        wxpayrefundrequest.setOutTradeNo(mtDeviceOrder.getOrderMainNo());
        //商户退款单号
        wxpayrefundrequest.setOutRefundNo(mtDeviceOrder.getOrderMainNo());
        //订单金额
        wxpayrefundrequest.setTotalFee(mtDeviceOrder.getOrderPayMoney().multiply(BigDecimal.valueOf(100)).intValue());
        //退款金额
        wxpayrefundrequest.setRefundFee(mtDeviceOrder.getOrderPayMoney().multiply(BigDecimal.valueOf(100)).intValue());

        WxPayRefundResult wxpayrefundresult = weChatMiniService.refund(wxpayrefundrequest);
        //调微信支付
        if ((wxpayrefundresult.getReturnCode().equals("SUCCESS") && wxpayrefundresult.getResultCode().equals("SUCCESS"))
                || (StrUtil.equals(alipayTradeRefundResponse.getMsg(), "Success") && StrUtil
                .equals(alipayTradeRefundResponse.getFundChange(), "Y"))) {
            mtDeviceOrder.setUpdateTime(DateUtil.currentSeconds());
            mtDeviceOrder.setOrderState(6);
            Validator.validateTrue(retBool(mtDeviceOrderMapper.updateById(mtDeviceOrder)), "退款失败!");
            //增加流水
            MtDeviceFlowingWater mtDeviceFlowingWater = new MtDeviceFlowingWater();
            mtDeviceFlowingWater.setSerialNo(mtDeviceOrder.getSerialNo());
            mtDeviceFlowingWater.setWaterUserId(mtDeviceOrder.getOrderUserId());
            mtDeviceFlowingWater.setWaterMoney(mtDeviceOrder.getOrderPayMoney().negate());
            mtDeviceFlowingWater.setWaterType(0);
            mtDeviceFlowingWater.setInoutType(1);
            mtDeviceFlowingWater.setWaterAccount(0);
            mtDeviceFlowingWater.setWaterExplain("设备异常退款");
            mtDeviceFlowingWater.setCreateTime(DateUtil.currentSeconds());
            mtDeviceFlowingWater.setCreateBy(SecurityUtils.getSysUser().getUserId());
            Validator.validateTrue(retBool(mtDeviceFlowingWaterMapper.insert(mtDeviceFlowingWater)), "支付回调失败!");
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * @Description: 设备订单异常反馈处理
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/19  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editFeedback(OrderComplaintStatusDto obj) {
        MtOrderComplaint dogNews = this.getById(obj.getId());
        Validator.validateNotNull(dogNews, "无此数据!");
        BeanUtil.copyProperties(obj, dogNews);
        dogNews.setUpdateTime(DateUtil.currentSeconds());
        dogNews.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        Validator.validateTrue(this.updateById(dogNews), "修改数据失败!");
        return Boolean.TRUE;
    }
}
